#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__title__ = ''
__author__ = 'tyh'
__mtime__ = '18-10-10'
# code is far away from bugs with the god animal protecting ~
"""

from django_redis import get_redis_connection
from rest_framework import serializers
from oauth import models
from oauth.models import OAuthQQUser
from oauth.utils import check_save_user_token
from users.models import User
from users.utils import generate_jwt_token


class QQAuthUserSerializer(serializers.ModelSerializer):

	access_token = serializers.CharField(label='操作凭证', write_only=True)
	# mobile = serializers.RegexField(label='手机号码', regex=r'^1[3-9]\d{9}$')
	# password = serializers.CharField(max_length=20, min_length=5, label='密码', write_only=True)
	sms_code = serializers.CharField(label='短信密码', write_only=True)

	token = serializers.CharField(label='登陆凭证', read_only=True)
	user_id = serializers.CharField(label='用户id', read_only=True)

	class Meta:
		model = User
		fields = ['mobile', 'password', 'token', 'username', 'sms_code', 'access_token','user_id']
		extra_kwargs = {'username': {'read_only': True, 'min_length': 5, 'max_length': 20,
			'error_messages': {'min_length': '仅允许5-20个字符的用户名', 'max_length': '仅允许5-20个字符的用户名', }},
			'password': {'write_only': True, 'min_length': 5, 'max_length': 20,
				'error_messages': {'min_length': '仅允许8-20个字符的密码', 'max_length': '仅允许8-20个字符的密码', }}}

	def validate(self, attrs):
		access_token = attrs['access_token']

		openid = check_save_user_token(access_token).get('openid')
		if not openid:
			raise serializers.ValidationError('无效的access_token')

		# 将openid放在校验字典中，后面会使用
		attrs['openid'] = openid

		# 检验短信验证码
		mobile = attrs['mobile']
		sms_code = attrs['sms_code']
		redis_conn = get_redis_connection('verify_code')
		real_sms_code = redis_conn.get('sms_%s' % mobile)
		if real_sms_code.decode() != sms_code:
			raise serializers.ValidationError('短信验证码错误')

		# 如果用户存在，检查用户密码
		try:
			user = User.objects.get(mobile=mobile)
		except User.DoesNotExist:
			pass
		else:
			password = attrs['password']
			if not user.check_password(password):
				raise serializers.ValidationError('密码错误')

			# 将认证后的user放进校验字典中，后续会使用
			attrs['user'] = user
		return attrs


	def create(self, validated_data):
		# 获取校验的用户
		user = validated_data.get('user')

		if not user:
			# 用户不存在,新建用户
			user = User.objects.create_user(username=validated_data['mobile'], password=validated_data['password'],
				mobile=validated_data['mobile'], )

		# 将用户绑定openid
		OAuthQQUser.objects.create(open_id=validated_data['openid'], user=user)
		# 返回用户数据
		user.token = generate_jwt_token(user)
		user.user_id = user.id
		# 向视图对象中补充user对象属性，以便在视图中使用user
		self.context['view'].user = user

		return user


if __name__ == '__main__':
	pass